var schedulesApp = angular.module("schedulesApp", ["ui.bootstrap","ngRoute"]);
//contextPath: Se obtiene desde el controlador y sirve para determinar la url actual

schedulesApp    
    .factory('schedules', dataFactory)
    .factory('utils',utilsFactory)
    .factory('gridConfig',gridConfigFactory)
    .service('modalService',modalService)
    .directive('ngJqgrid', ngJqgrid)
    .directive('angucomplete',angucomplete)
    .config(function ($routeProvider, $locationProvider) {
        $locationProvider.hashPrefix('!');
        $routeProvider
            .when('/index',
                {
                    controller: 'indexController',
                    templateUrl: 'index.html'
                })        
            .when('/edit/:id',
                {
                    controller: 'editScheduleController',
                    templateUrl: 'edit.html'
                })
            .when('/add',
                {
                    controller: 'editScheduleController',
                    templateUrl: 'edit.html'
                })
            .otherwise({ redirectTo: '/index' });
    })
    .run(function($rootScope,schedules){
       
       $rootScope.pointStatus = [
           {id:0, status:'Sin estatus'},
           {id:1, status:'Normal'},
           {id:2, status:'Pausado'},
           {id:3, status:'Cancelado'}
       ];
       
        $rootScope.pointAvailability = [
           {id:1, tipo:'Obligatorio'},
           {id:0, tipo:'No obligatorio'}
       ];
    });


schedulesApp.controller("indexController", function($rootScope,$scope, $location, schedules, modalService, gridConfig) {
    $scope.init = function(){
        $(window).on('resize', function(event, ui) {
            var parWidth = $("#gbox_grdSchedules").parent().parent().parent().width();
            var curWidth = $("#gbox_grdSchedules").width();
            var w = parWidth - 1;
            if (Math.abs(w - curWidth) > 2)
            {  
                $("#grdSchedules").setGridWidth(w);
            }
        }).trigger('resize');
    }
    $scope.grid = {};
    
    $scope.refresh = function(){
        $scope.grid.api.refresh();
    }
    
    $scope.goEdit = function(path){
        if($scope.scheduleId)
           $scope.go(path); 
        else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder editar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    $scope.go = function ( path ) {
        $location.path( path );
    };
    
    $scope.delete = function(id){
        if (id) {
            var modalOptions = {
                closeButtonText: 'Cancelar',
                actionButtonText: 'Eliminar',
                bodyText: '¿Estás seguro de eliminar esta Programación?'
            };
            modalService.showModal({}, modalOptions).then(function (result) {
                $scope.loading = true;
                schedules.delete(contextPath + "delete", {id: id})
                .success(function(data, status, headers, config) {
                    $scope.loading = false;
                    if(data.error){
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: data.error
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }else{
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: '¡Registro eliminado con éxito!'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result){
                             $scope.grid.api.refresh();
                        });
                    }                   
                    })
                .error(function(data, status, headers, config) {
                    $scope.loading = false;
                    var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: 'Ocurrió un error al eliminar el registro.'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                });
            });
        }else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder eliminar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    
    $scope.grid.config = gridConfig.config({
	url: contextPath + "getSchedules",
	colNames: ["id","route_id","Ruta","Última programación","user_id","Conductor","vehicle_id","Vehículo","status","Estatus", "monday","tuesday","wednesday","thursday","friday","saturday","sunday","recurrent","Periódica","week","Semanal","scheduleParent_id"],
	colModel: [                
		{name: "id", width: 0, align: "right", hidden: true},
                {name: "route_id", index:"route_id", width: 0, align: "right", hidden: true},
                {name: "route", index:"route", width: 100, align: "left"},
                {name: "start_date", index:"start_date", width: 70, formatter: 'date', formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'd-m-Y h:i A'}},
                {name: "user_id", index:"user_id", width: 0, align: "right", hidden: true},
                {name: "driver", index:"driver", width: 100},
                {name: "vehicle_id", index:"vehicle_id", width: 0, align: "right", hidden: true},
                {name: "vehicle", index:"vehicle", width: 100},                
                {name: "status", index:"status", width: 0, hidden: true},
		{name: "estatus", index:"estatus", width: 40},
                {name: "monday", index:"monday", width: 0, hidden: true},
                {name: "tuesday", index:"tuesday", width: 0, hidden: true},
                {name: "wednesday", index:"wednesday", width: 0, hidden: true},
                {name: "thursday", index:"thursday", width: 0, hidden: true},
                {name: "friday", index:"friday", width: 0, hidden: true},
                {name: "saturday", index:"saturday", width: 0, hidden: true},
                {name: "sunday", index:"sunday", width: 0, hidden: true},
                {name: "recurrent", index:"recurrent", width: 0, hidden: true},
                {name: "periodica", index:"periodica", width: 40, align: "center"},
                {name: "week", index:"week", width: 0, hidden: true},
                {name: "semanal", index:"semanal", width: 40, align: "center"},
                {name: "scheduleParent_id", index:"scheduleParent_id", width: 0, hidden: true}
	],
	sortname: "start_date",
	sortorder: "desc",
	caption: "Programación de Rutas",
        onSelectRow: function(id){
            $scope.$apply(function(){
                $scope.selRow = id;
                $scope.scheduleId = $scope.grid.apicall('getRowData', id).id
            });
        },
        beforeRequest: function(){
        },
        loadComplete: function (data) {
            $scope.$apply(function(){
                $rootScope.data = data; 
                $scope.selRow =null;
                $scope.scheduleId = null;
            });
            $scope.init();
        }
    },{id:"id"});
});

schedulesApp.controller("editScheduleController", function($rootScope,$scope, $filter, $location, $routeParams, schedules, utils, modalService, gridConfig) {
    $scope.sc = {loading:false, frmSchedule:{}}
    $scope.vehicleContextPath = vehicleContextPath;
    $scope.userContextPath = userContextPath;
    $scope.routeContextPath = routeContextPath;
    
    init();
    
    /*Datepicker*/
    $scope.datePicker = {}
    $scope.datePicker.format = 'dd-MM-yyyy';
    
    $scope.datePicker.toggleMin = function() {
        $scope.datePicker.minDate = $scope.datePicker.minDate ? null : new Date();
    };
    $scope.datePicker.toggleMin();
  
    $scope.datePicker.open = function($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.datePicker.opened = true;
    };
    
    $scope.datePicker.dateOptions = {
        formatYear: 'yy',
        startingDay: 1        
    };
    
    $scope.datePicker.disabled = function(date, mode) {
        return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
    };  
    /*Datepicker*/
    
    /*Autocomplete*/
    $scope.sc.cboVehicles = {};    
    $scope.$watch('sc.cboVehicles.selectedObject', function(newValue, oldValue) {
        if (newValue != null) {
            $scope.schedule.vehicle_id = newValue.originalObject.id;
            $scope.schedule.vehicle = newValue.originalObject.name;
        }
        else {
            if(!(typeof(newValue)=='undefined' && typeof(oldValue)=='undefined')){
                $scope.schedule.vehicle_id = null;
                $scope.schedule.vehicle = null;
            }
        }
    });
    
    $scope.sc.cboUsers = {};    
    $scope.$watch('sc.cboUsers.selectedObject', function(newValue, oldValue) {
        if (newValue != null) {
            $scope.schedule.user_id = newValue.originalObject.id;
            $scope.schedule.driver = newValue.originalObject.driver;
        }
        else {
            if(!(typeof(newValue)=='undefined' && typeof(oldValue)=='undefined')){
                $scope.schedule.user_id = null;
                $scope.schedule.driver = null;
            }
        }
    });
    
    $scope.sc.cboRoute = {};    
    $scope.$watch('sc.cboRoutes.selectedObject', function(newValue, oldValue) {
        if (newValue != null) {
            $scope.schedule.route_id = newValue.originalObject.id;
            $scope.schedule.route = newValue.originalObject.route;
        }
        else {
            if(!(typeof(newValue)=='undefined' && typeof(oldValue)=='undefined')){
                $scope.schedule.route_id = null;
                $scope.schedule.route = null;
            }
        }
    });    
    /*Autocomplete*/
    
    $scope.go = function ( path ) {
        $location.path( path );
    };
    
    function init() {
        //Catálogos Iniciales
        $scope.routeStatus = [{id:0, status:'Inactiva'},{id:1, status:'Activa'}]
       
        //Asignaciones iniciales
        $scope.schedule = {};
        var today = new Date();
        $scope.sc.dt = today;
        var scheduleId = ($routeParams.id) ? parseInt($routeParams.id) : 0;
        if (scheduleId > 0) {
            if($scope.data){
                $scope.schedule = utils.findById($scope.data[0],'id',scheduleId)
                if(!$scope.schedule){
                    $scope.go("/index");
                     return;
                }
                $rootScope.schedule = $scope.schedule;
                var st = $scope.schedule.start_date;
                $scope.sc.dt = utils.getDateFromString(st);
            }else{
                $scope.sc.loading = true;
                schedules.getData(contextPath + "getSchedules", {page: 1, rowsPerPage: 1, sortField: 'start_date', sortDir: 'desc', id: scheduleId})
                    .success(function(data, status, headers, config) {
                        $scope.sc.loading = false;
                        if(!data[0][0]){
                            $scope.go("/index");
                            return;
                        }
                        $scope.schedule = data[0][0];
                        $rootScope.schedule = $scope.schedule;
                        var st = $scope.schedule.start_date; 
                        $scope.sc.dt = utils.getDateFromString(st);
                        
                    })
                    .error(function(data, status, headers, config) {
                        alert('Error');
                    });
            }
        }else{
            $scope.schedule= {monday:0, tuesday:0, wednesday:0, thursday:0, friday:0, saturday:0, sunday:0, status:1, week:0, recurrent:0};
        }
    }
    
    $scope.save = function(){
        if($scope.schedule){
            $scope.sc.loading=true;
            $scope.schedule.start_date = $filter('date')($scope.sc.dt, 'yyyy-MM-dd HH:mm:ss');
            
            schedules.save(contextPath + "save", $scope.schedule, {})
                .success(function(data, status, headers, config){
                    $scope.sc.loading=false;
                    if (data.error) {
                         var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: data.error
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    } else {
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: '¡Registro guardado con éxito!'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result) {
                                $location.path('/index');
                            });
                        }
                })
                .error(function(data, status, headers, config){
                    $scope.sc.loading = false;
                    alert('Error');
                });
        }
    }
    
    $scope.getFormFieldCssClass = function(ngModelController) {
        if(ngModelController.$pristine) return "";
        return ngModelController.$valid ? "has-success" : "has-error";
    }
    
    
});
